package com.jesper.seckill.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.jesper.seckill.constant.UserConstant;
import com.jesper.seckill.entity.po.User;
import com.jesper.seckill.service.IUserService;
import com.jesper.seckill.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;


/**
 * 自定义的参数解析器
 */
@Service
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private IUserService userService;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //当参数为user才处理
        Class<?> parameterType = parameter.getParameterType();
        return parameterType == User.class;
    }

    /**
     * 思路：先获取到已有参数HttpServletRequest，从中获取到token，再用token作为key从redis拿到User，而HttpServletResponse作用是为了延迟有效期
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeRequest(HttpServletResponse.class);
        String tokenName = request.getParameter(UserConstant.COOKIE_NAME_TOKEN);
        String tokenValue = this.getCookieValue(request, tokenName);
        if (StrUtil.isBlank(tokenValue)){
            return null;
        }
        return tokenUtil.getUidOrNull(tokenValue);
    }

    /**
     * 遍历所有cookie，找到需要的那个cookie
     */
    private String getCookieValue(HttpServletRequest request,String cookieName){
        if (StrUtil.isBlank(cookieName)){
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (ArrayUtil.isEmpty(cookies)){
            return null;
        }
        return Arrays.stream(cookies)
                .filter(c -> c.getName().equals(cookieName))
                .map(Cookie::getValue)
                .findFirst()
                .orElse(null);
    }
}
